﻿using CommunityToolkit.Maui.Alerts;
using Compass.Maui.Services.FinishGoods;

namespace Compass.Maui.ViewModels.FinishGoods;

[QueryProperty(nameof(Result), nameof(Result))]
[QueryProperty(nameof(PackingListDto), nameof(PackingListDto))]
public partial class WarehousingPalletPageViewModel : BaseViewModel
{
    private readonly IPalletService _palletService;
    public WarehousingPalletPageViewModel()
    {

        _palletService = Ioc.Default.GetRequiredService<IPalletService>();
        Locations = Enum.GetNames(typeof(WarehouseLocation_e));
    }

    [ObservableProperty]
    private string result;
    [ObservableProperty]
    private PackingListDto packingListDto;

    //根据id查询到PalletDto，修改入库日期和库位
    //todo:拍照确认？
    //回传Pallet
    [ObservableProperty]
    private PalletDto palletDto;
    [ObservableProperty]
    private string[] locations;


    [RelayCommand]
    private async Task GetPalletDtoAsync()
    {
        var id = Enumerable.Last<string>(Result.Split('_'));
        PalletDto = await _palletService.GetFirstOrDefaultAsync(Guid.Parse(id))??new PalletDto();
        //如果是空的就将入库日期设置为现在
        PalletDto.WarehousingTime ??= DateTime.Now;
    }

    [RelayCommand]
    private async Task GoBackAsync()
    {
        await Shell.Current.GoToAsync("..",
            new Dictionary<string, object?>
            {
                {nameof(PackingListDto),PackingListDto}
            });
        //await Shell.Current.Navigation.PopModalAsync();

    }

    [RelayCommand]
    private async Task WarehousingAsync()
    {
        await _palletService.UpdateStatusesWithEventAsync(PalletDto.Id.Value, PalletDto);

        await GoBackAsync();
    }

    [RelayCommand]
    private async Task UnWarehousingAsync()
    {
        //弹窗确认
        var yesNo = await Application.Current!.MainPage!.DisplayAlert("询问", "确定要取消入库吗？", "Yes", "No");
        if (yesNo)
        {
            if (PalletDto.ShippingTime!=null)
            {
                await Toast.Make("此托盘已经发货，无法取消入库。").Show();
                return;
            }

            PalletDto.WarehousingTime = null;
            await _palletService.UpdateStatusesWithEventAsync(PalletDto.Id.Value, PalletDto);

            await GoBackAsync();
        }
    }
}